﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace Sharp.UnusedReferences.Options
{
	public partial class UserControlOptionsEntry : UserControl
	{
		#region Fields

		object DefaultValue;
		object ObjectToBeRest;
		PropertyInfo PropertyToBeReset;

#endregion
		
		#region Constructors
		
		public UserControlOptionsEntry(object ObjectToBeRest, PropertyInfo PropertyToBeReset, bool ShowHeader)
		{
			InitializeComponent();
			this.ObjectToBeRest = ObjectToBeRest;
			this.PropertyToBeReset = PropertyToBeReset;
			if(!ShowHeader)
			{
				TableLayoutPanelMain.SuspendLayout();
				TableLayoutPanelMain.Controls.RemoveAt(TableLayoutPanelMain.Controls.Count - 1);
				TableLayoutPanelMain.Controls.RemoveAt(TableLayoutPanelMain.Controls.Count - 1);
				TableLayoutPanelMain.Controls.RemoveAt(TableLayoutPanelMain.Controls.Count - 1);
				foreach(Control ControlInstance in this.TableLayoutPanelMain.Controls)
				{
					TableLayoutPanelMain.SetRow(ControlInstance, 0);
				}
				TableLayoutPanelMain.RowStyles.RemoveAt(1);
				TableLayoutPanelMain.RowCount = 2;
				TableLayoutPanelMain.ResumeLayout(false);
				TableLayoutPanelMain.PerformLayout();
			}
			PopulateProperty();
		}

#endregion
		
		#region Public Functions
		
		internal void RefreshValue()
		{
			LabelCurrentValue.Text = Convert.ToString(PropertyToBeReset.GetValue(ObjectToBeRest, null));
			SetToolTip(LabelCurrentValue);
			ButtonReset.Enabled = LabelDefaultvalue.Text != LabelCurrentValue.Text;
			LabelCurrentValue.ForeColor = (ButtonReset.Enabled) ? Color.Red : Color.Black;
		}

		#endregion

		#region Events' Handlers
		
		private void ButtonReset_Click(object sender, EventArgs e)
		{
			PropertyToBeReset.SetValue(ObjectToBeRest, DefaultValue, null);
			RefreshValue();
		}

		#endregion
		
		#region Helper Functions

		private void PopulateProperty()
		{
			foreach(object objectCustomAttribute in PropertyToBeReset.GetCustomAttributes(false))
			{
				if(objectCustomAttribute is DisplayNameAttribute)
				{
					LabelOptionName.Text = ((DisplayNameAttribute)objectCustomAttribute).DisplayName;
					SetToolTip(LabelOptionName);
				}
				else if(objectCustomAttribute is DefaultValueAttribute)
				{
					DefaultValue = ((DefaultValueAttribute)objectCustomAttribute).Value;
					LabelDefaultvalue.Text = Convert.ToString(DefaultValue);
					SetToolTip(LabelDefaultvalue);
				}
			}
			RefreshValue();
		}
		private void SetToolTip(Control ControlInstancee)
		{
			ToolTipMain.SetToolTip(ControlInstancee, ControlInstancee.Text);
		}
	
		#endregion
	}
}
